<?php

namespace app\shop\controller\setting;

use app\shop\model\product\BrandModel;
use app\Request;
use app\shop\controller\Controller;
use app\shop\model\settings\DicModel;

/**
 * 用户管理
 */
class Dic extends Controller
{
    /**
     * 商户列表
     */
    public function index(Request $request)
    {
        $where    = $request->param();
        $list     = DicModel::listData($where, $this->getData(), ['proxy']);
        $category = config('dic');
        $model    = new DicModel;
        // 数量
        $category_count = [
            'using'   => $model->getTotalByWhere(['audit_status' => 1]),
            'audit'   => $model->getTotalByWhere(['audit_status' => 0]),
            'no_pass' => $model->getTotalByWhere(['audit_status' => 2]),
        ];
        return $this->renderSuccess('', compact('list', 'category', 'category_count'));
    }

    public function create(Request $request)
    {
        try {
            $where = $request->param();
            // 新增记录
            $result = DicModel::createData($where);
            return $this->renderSuccess('操作成功', $result);
        } catch (\Exception $exception) {
            return $this->renderError($exception->getMessage());
        }
    }

    public function edit(Request $request)
    {
        $where = $request->param();
        // 用户详情
        $model = DicModel::one($where);
        return $this->renderSuccess('', compact('model'));

    }

    public function update(Request $request)
    {
        $params = $request->param();
        // 修改记录
        $model = DicModel::detail($params['id']);
        $model->save($params);
        return $this->renderSuccess('修改成功');
    }

    public function delete(Request $request)
    {
        $params = $request->param();
        // 修改记录
        DicModel::deleteData($params);
        return $this->renderSuccess('删除成功');
    }

    public function category()
    {
        return $this->renderSuccess('', config('dic'));
    }

    public function getshare()
    {
        return $this->renderSuccess('', config('share'));
    }

    /**
     * 审核商城配置
     * @return \think\response\Json
     * @Author joey
     * @date 2024/3/27 10:55
     */
    public function audit()
    {
        $param  = $this->postData();
        $model  = new DicModel;

        if (!isset($param['id'])) {
            return $this->renderError('商城配置id不能为空');
        }
        $param['id'] = is_array($param['id']) ? $param['id'] : [$param['id']];
        $detail      = $model->whereIn('id', $param['id'])->select();
        if ($detail->isEmpty()) {
            return $this->renderError('商城配置不存在');
        }
        $data = ['audit_status' => $param['audit_status'], 'remark' => $param['remark'] ?? ''];
        $num = 0;
        foreach ($detail as $item) {
            $res = $item->allowField(['audit_status', 'remark'])->save($data);
            if ($res) {
                $num++;
            }
        }
        return $this->renderSuccess($num > 0 ? "审核成功{$num}条" : '审核失败');
    }
}
